package com.lhl.jwt.security.handler;

import cn.hutool.core.util.StrUtil;
import com.lhl.jwt.security.service.JwtUserDetailsService;
import com.lhl.jwt.security.utils.JwtConstant;
import com.lhl.jwt.security.utils.JwtUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @className: com.lhl.jwt.security.handler.LoginSuccessHandler
 * @description: 登录成功返回token
 * @author: king
 * @date: 2020-12-21 23:32
 **/
@Api(tags = "LoginSuccessHandler", produces = "LoginSuccessHandler")
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private JwtUserDetailsService jwtUserDetailsService;
    public LoginSuccessHandler(JwtUserDetailsService jwtUserDetailsService) {
        this.jwtUserDetailsService = jwtUserDetailsService;
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        UserDetails user = (UserDetails)authentication.getPrincipal();
        String token = generToken((UserDetails)authentication.getPrincipal(), getSalt(user.getUsername()));

        jwtUserDetailsService.insertSalt(token, user);
        response.setHeader(JwtConstant.AUTHORIZATION_HEADER, JwtConstant.AUTHORIZATION_START_STRING + token);
        response.setHeader(JwtConstant.ACCESS_CONTROL_EXPOSE_HEADER, JwtConstant.AUTHORIZATION_HEADER);

        log.info("Login success! token : {}", token);
    }

    private String generToken(UserDetails user, String salt) {
        return JwtUtils.createToken(user.getUsername(), user.getAuthorities(), salt);
    }

    private String getSalt(String username) {
        String salt = jwtUserDetailsService.getSalt(username);
        if (StrUtil.isBlank(salt)) {
            salt = JwtUtils.TOKEN_SECRET;
        }
        return salt;
    }
}
